import { createStore } from 'vuex'
import { login, logout, getUserInfo, register } from '@/api/auth'

// 角色映射表
const ROLE_MAP = {
  0: 'user',
  1: 'admin',
  2: 'volunteer',
  3: 'organization'
}

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token'),
    activities: [],
    news: [],
    userRoles: {
      ADMIN: 'admin',
      USER: 'user',
      VOLUNTEER: 'volunteer',
      ORGANIZATION: 'organization'
    }
  },
  getters: {
    isAdmin: state => state.user?.role === 1,
    isVolunteer: state => state.user?.role === 2,
    isOrganization: state => state.user?.role === 3,
    isUser: state => state.user?.role === 0,
    // 获取映射后的角色名称
    mappedRole: state => ROLE_MAP[state.user?.role] || 'user',
    userPermissions: (state) => {
      const roleNumber = state.user?.role
      switch(roleNumber) {
        case 1: // admin
          return {
            canManageUsers: true,
            canManageContent: true,
            canManageActivities: true,
            canManageNews: true,
            canManageDonations: true
          }
        case 3: // organization
          return {
            canManageUsers: false,
            canManageContent: false,
            canManageActivities: true,
            canManageNews: false,
            canManageDonations: true
          }
        case 2: // volunteer
          return {
            canManageUsers: false,
            canManageContent: false,
            canManageActivities: false,
            canManageNews: false,
            canManageDonations: false,
            canParticipateActivities: true,
            canViewCertificates: true
          }
        case 0: // user
          return {
            canManageUsers: false,
            canManageContent: false,
            canManageActivities: false,
            canManageNews: false,
            canManageDonations: false,
            canDonate: true,
            canRegisterVolunteer: true
          }
        default:
          return {}
      }
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    setUser(state, user) {
      // 确保用户对象包含数字角色值
      if (user && typeof user.role === 'number') {
        state.user = {
          ...user,
          roleName: ROLE_MAP[user.role] // 添加映射后的角色名称
        }
      } else {
        state.user = user
      }
    },
    setActivities(state, activities) {
      state.activities = activities
    },
    setNews(state, news) {
      state.news = news
    },
    logout(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 登录
    async login({ commit }, credentials) {
      try {
        const response = await login(credentials)
        console.log('Store 收到登录响应：', response)
        
        // 确保响应格式正确
        if (!response || !response.code || response.code !== 200) {
          throw new Error(response?.message || '登录失败')
        }
        
        // 获取 token 和用户信息
        const { token, user } = response.data
        
        if (!token || !user) {
          throw new Error('登录响应数据不完整')
        }
        
        commit('setToken', token)
        commit('setUser', user)
        return user  // 直接返回用户信息
      } catch (error) {
        console.error('Store 登录错误：', error)
        commit('logout')
        throw error
      }
    },
    
    // 注册
    async register({ commit }, userData) {
      try {
        const response = await register(userData)
        
        // 确保响应格式正确
        if (!response || !response.code || response.code !== 200) {
          throw new Error(response?.message || '注册失败')
        }
        
        return response.data
      } catch (error) {
        console.error('Store 注册错误：', error)
        throw error
      }
    },
    
    // 获取用户信息
    async getUserInfo({ commit }) {
      try {
        const user = await getUserInfo()
        commit('setUser', user)
        return user
      } catch (error) {
        commit('logout')
        throw error
      }
    },
    
    // 登出
    async logout({ commit }) {
      try {
        await logout()
      } finally {
        commit('logout')
      }
    }
  },
  modules: {
  }
}) 